//配置路由相关信息
// 1.首先导入路由
import Router from 'vue-router'
import Vue from 'vue'

// import Home from '../components/Home'
// import About from "../components/About";
// import User from "../components/User";

//使用懒加载
const Home = ()=>import('../components/Home')
const HomeNews =()=>import('../components/HomeNews')
const HomeMessage =()=>import('../components/HomeMessage')
const About = ()=>import('../components/About')
const User = ()=>import('../components/User')
const Profile = ()=>import('../components/Profile')

//通过Vue.use(Vue的插件)，来安装插件，所以在此之前需要先导入Vue
Vue.use(Router)

//2.创建路由对象,在这里配置映射关系
const routes =[
  {
    path: '',
    //redirect重定向
    redirect:'/home'
  },
  {
    //只要路径中出现/home就调用下面的组件
    path:'/home',
    component:Home,
    meta:{
      title:'首页'
    },
    children:[
      //默认路径
      // {
      //   path: '',
      //   redirect:'/home/news'
      // },
      {
        path:'news',
        component:HomeNews
      },
      {
        path:'message',
        component:HomeMessage
      },
    ]
  },
  {
    path:'/about',
    meta: {
      title: '关于'
    },
    component:About,
    beforeEnter:(to,from,next)=>{
      // console.log('开始进入路由独享守卫')
      next()
    },
  },
  {
    path: '/user/:userId',
    meta: {
      title: '用户',
    },
    component:User
  },
  {
    path: '/profile',
    meta: {
      title: '档案',
    },
    component:Profile
  },
]

const router = new Router({
  //在routes中配置路由和组件之间的应用关系
  routes,
  mode:'history',
  linkActiveClass:'active'
})

//前置钩子（前置回调，在跳转之前进行的回调   回调函数也称为钩子函数）
router.beforeEach((to,from,next)=>{
  //从from跳转到to
  document.title = to.matched[0].meta.title
  // console.log('路由跳转开始')
  next()
})

//后置钩子(hook)，后置守卫    在路由跳转完成后执行
router.afterEach((to,from)=>{
  // console.log('路由跳转完成')
})

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 3.将router对象传入到vue实例
export default router


